<?php

namespace App\Http\Controllers\Api;

use App\Services\Aliyun\Video\VideoServices;
use App\Services\Aliyun\Video\VideoWatermarkServices;
use App\Services\Aliyun\upload\AliyunUploadServices;
use App\Services\Configs\DefaultService;
use App\Services\SevenCattle\UploadServices as sevenUploadServices;
use App\Services\Tencent\UploadServices;
use App\Models\ImFilesStorage;
use Illuminate\Http\Request;

class UploadController
{
    /**上传图片或者视频**添加智能图片/视频审核**设置权限
     * @param Request $request
     * file  上传文件绝对路劲
     * folder 自定义上传到对应的桶的文件夹（自动创建）
     * bucket 自定义上传到指定桶（自动创建）
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadImg(Request $request)
    {
        $param = $request->all();
        $file = $request->file('file');

        if (empty($file)) {
            return errBack('未上传文件！');
        }
        if (empty($param['folder'])) {
            return errBack('请指定上传文件夹名称！(自定义)');
        }
        if (empty($param['type'])) {  //1图片，2视频
            return errBack('请指定上传文件类型');
        }
        if (empty($param['power'])) {  //私有1, 公共读2,公共读写3
            return errBack('请指定上传文件的权限类型');
        }
        if (empty($param['source'])) {  // 1总后台，2APP
            return errBack('请指定来源');
        }
        if (empty($param['vendor'])) {  //平台
            return errBack('请指定来源平台');
        }
        if (empty($param['examine'])) {  //是否需要审核  1需要  2不需要
            return errBack('请指定是否需要审核');
        }
        $user = $request->user();
        $userId = $user->id;
        $param['examine'] = 2;  //默认不提交智能审核
        if($param['type']==1){//图片
            switch ($param['vendor']) {
                case 1:   //七牛云
                    $sevenUploadServices =  new sevenUploadServices();
                    $res = $sevenUploadServices->sevenUpload($file,$param['folder'], $param['power']);
                    $etag = $res['hash'];
                    $fileUrl = $res['key'];
                    if($param['power']==1){//私有的需要授权之后才能提交智能审核
                        $downloadUrl = $sevenUploadServices->downloadUrl($res['key'],3600000);//过期时间
                    }
                    break;
                case 2:   //阿里云
                    $aliyunUpload = new AliyunUploadServices();
                    $res = $aliyunUpload->uploadImg($file, $param['folder'], $param['power']);
                    $etag = trim($res['etag'], '"');//文件的标识 图片
                    $fileUrl = $res['info']['url'];//返回的文件地址
                    if($param['power']==1){//私有的需要授权之后才能提交智能审核
                        $url = explode('com/',$fileUrl);
                        $downloadUrl = $aliyunUpload->downloadUrl($url[1],3600000);//过期时间
                    }
                    break;
                case 3:  //腾讯云
                    $uploadServices = new UploadServices(DefaultService::TENCENT_OSS);
                    $res = $uploadServices->uploadImg($file, $param['folder'], $param['power']);
                    $etag =trim($res['ETag'], '"');//文件的标识 图片
                    $fileUrl = 'https://'.$res['Location'];
                    if($param['power']==1){//私有的需要授权之后才能提交智能审核
                        $downloadUrl = $uploadServices->getObjectUrl($res['Key']);
                    }
                    break;
                default:
            }
        }else{//阿里云视频点播转码
            $transcodingVideo = new VideoServices();
            $res =  $transcodingVideo->transcodingVideo($file);
            $fileUrl = $res['info']['url'];//原视频播放地址
            $etag = trim($res['etag'], '"');//文件的标识  视频
            $videoId = $res['video_id'];//刷新视频上传凭证video_id
              //获取转码和水印后的视频详细信息(处理后的视频播放地址）会延迟5s 不能马上获取
//            $newUrl = $transcodingVideo->getVideoPlayUrl($videoId');//获取转码和水印后的视频播放地址
              $newUrl = '';
            $downloadUrl ='';
        }
        if ($res !== 1) {//成功
            if($param['examine'] ==1){   //需要提交智能视频/图片审核
                $fileAIMediaAuditJob = new VideoServices();
                if($param['power']==1){//私有的需要使用授权之后的url才能提交智能审核  智能审核目前是同步审核， 拿返回的task_id 去跑查数据库跑脚本审核，还有一种是异步配置URL审核(类似支付回调)
                    $taskId = $fileAIMediaAuditJob->submitAIMediaAuditJob($downloadUrl, $param['type']); //type=1提交图片  2视频  $taskId智能检测任务ID(可获取智能检查结果）
//                    $res =  $transcodingVideo->getAIMediaAuditJobInfo($taskId',2);$taskId智能检测任务ID(可获取智能检查结果）

                }else{
                    $taskId = $fileAIMediaAuditJob->submitAIMediaAuditJob($fileUrl, $param['type']); //type=1提交图片  2视频  $taskId智能检测任务ID(可获取智能检查结果）
                }
            }else{
                $taskId = '';
            }
            //数据入库
            $file = new ImFilesStorage();
            $videoId =  !empty($videoId) ? $videoId : '' ;
            $file->addFilesStorage($param['type'], $etag, $param['source'], $fileUrl, $userId, $taskId, $param['vendor'],$videoId,$param['power']);
            if($param['type']==2){
                return okBack('0', ['url' => $fileUrl, 'key' => $etag, 'task_id' => $taskId,'video_id'=>$videoId,'newUrl'=>$newUrl]);
            }
            return okBack('0', ['url' => $fileUrl, 'key' => $etag, 'task_id' => $taskId]);
        } else {
            return errBack('上传失败1！');
        }
    }

    /**
     *授权获取私有文件url
     * @param Request $request
     *author:tangfen
     *date:$ct
     */
    public function privateDownloadUrl(Request $request){
        $url = $request->url;
        $type = $request->type;
        if (empty($url) || empty($type)) {
            return errBack('缺少参数！');
        }
        switch ($type){
            case 1:   //七牛云
                $sevenUploadServices =  new sevenUploadServices();
                $downloadUrl = $sevenUploadServices->downloadUrl($url,3600000);//过期时间
                break;
            case 2:   //阿里云
                $aliyunUpload = new AliyunUploadServices();
                $url = explode('com/',$url);
                $downloadUrl = $aliyunUpload->downloadUrl($url[1],3600000);//过期时间
                break;
            case 3:  //腾讯云
                $url = explode('com/',$url);
                $uploadServices = new UploadServices(DefaultService::TENCENT_OSS);
                $downloadUrl = $uploadServices->getObjectUrl($url[1],3600000);
                break;
            default:
        }
        return okBack('0', ['download_url' => $downloadUrl]);
    }

    /**
     *删除文件
     * @param Request $request
     *author:tangfen
     *date:$ct
     */
    public function delFile(Request $request){
        $fileUrl = $request->fileUrl;
        if (empty($fileUrl)) {
            return errBack('缺少参数！');
        }
        $ImFilesStorage = new ImFilesStorage();
        $type = $ImFilesStorage->where('link_url', $fileUrl)->value('vendor'); //所属平台
        switch ($type){
            case 1:   //七牛云
                $sevenUploadServices =  new sevenUploadServices();
                $res = $sevenUploadServices->delFile($fileUrl);
                break;
            case 2:   //阿里云
                $aliyunUpload = new AliyunUploadServices();
                $res = $aliyunUpload->delFile($fileUrl);
                break;
            case 3:  //腾讯云
                $uploadServices = new UploadServices(DefaultService::TENCENT_OSS);
                $res = $uploadServices->delFile($fileUrl);
                break;
            default:
        }
        if($res!=1){
            return okBack('0','删除成功');
        }
    }

    /**
     *阿里云视频点播获取处理后的视频播放地址 转码/水印（延迟5s）
     *author:tangfen
     *date:$ct
     */
    public function getVideoPlayUrl(Request $request){
        $videoId = $request->videoId;
        if (empty($videoId)) {
            return errBack('缺少参数！');
        }
        $transcodingVideo = new VideoServices();
        $res = $transcodingVideo->getVideoPlayUrl($videoId,3600*200000);//转码水印之后的播放地址
        return okBack('0', ['data' =>$res]);
    }

    /**
     * 文本上传(提交智能检测)
     * textName 文件名称(不需要后缀)
     * contents 填写待上传的字符串。
     */
    public function uploadIext(Request $request)
    {
        $content = $request->contents;
        if (empty($content)) {
            return errBack('缺少参数！');
        }

        //提交智能文本审核
        $fileAIMediaAuditJob = new VideoServices();
        $data = $fileAIMediaAuditJob->submitTextAIMediaAuditJob($content); //$taskId智能检测任务ID(可获取智能检查结果）
        return okBack('0', ['data' => $data]);
    }

    /**
     * 获取智能审核信息
     */
    public function getAIMediaAuditJobInfo(Request $request)
    {
        $taskId = $request->taskId;
        $type = $request->type; //1图片 2视频
        if (empty($taskId) || empty($type)) {
            return errBack('缺少参数!');
        }
        $fileAIMediaAuditJob = new VideoServices();
        $res = $fileAIMediaAuditJob->getAIMediaAuditJobInfo($taskId, $type); //$taskId智能检测任务ID(可获取智能检查结果）

        return okBack('0', $res);
    }


    /**下载图片或者视频
     * @param Request $request
     * url 保存的阿里云oss图片地址
     * @return \Illuminate\Http\JsonResponse
     */
    public function downloadImg(Request $request)
    {
        $url = $request->url;
        if (empty($url)) {
            return errBack('请上传图片！');
        }
        //上传阿里云文字
        $aliyunUpload = new AliyunUploadServices();
        $localfile = $aliyunUpload->downloadImg($url);
        if ($localfile !== 1) {//成功
            return okBack('0', ['url' => '/' . $localfile]);
        } else {
            return errBack('获取失败！');
        }
    }

    /**获取图片信息
     * @param Request $request
     * url 保存的阿里云oss图片地址
     * @return \Illuminate\Http\JsonResponse
     */
    public function getImg(Request $request)
    {
        $etag = $request->etag;
        if (empty($etag)) {
            return errBack('缺少参数etag');
        }
        $aliyunUpload = new AliyunUploadServices();
        $data = $aliyunUpload->getImg($etag);
        if ($data !== 1) {
            return okBack('0', ['data' => $data]);
        } else {
            return errBack('获取失败！');
        }
    }

    /**设置文件的元信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author tangfen
     */
    public function setUploadInformation(Request $request)
    {
        $fileUrl = $request->fileUrl;
        $expiresTime = $request->expiresTime;
        $title = $request->title;
        $content = $request->contents;
        if (empty($fileUrl) || empty($title) || empty($expiresTime) || empty($content)) {
            return errBack('缺少参数');
        }
        $aliyunUpload = new AliyunUploadServices();
        $data = $aliyunUpload->setUploadInformation($fileUrl, $expiresTime, $title, $content);
        if ($data !== 1) {
            return okBack('0', ['data' => $data]);
        } else {
            return errBack('获取失败！');
        }
    }

    /**修改文件元信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author tangfen
     */
    public function updateUploadInformation(Request $request)
    {
        $fileUrl = $request->fileUrl;
        $expiresTime = $request->expiresTime;
        $title = $request->title;
        $toObject = $request->toObject;  //修改的文件名称
        if (empty($fileUrl) || empty($title) || empty($expiresTime) || empty($toObject)) {
            return errBack('缺少参数');
        }
        $aliyunUpload = new AliyunUploadServices();
        $data = $aliyunUpload->updateUploadInformation($fileUrl, $expiresTime, $title, $toObject);
        if ($data !== 1) {
            return okBack('0', ['data' => $data]);
        } else {
            return errBack('获取失败！');
        }
    }

    /**获取文件元信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author tangfen
     */
    public function getUploadInformation(Request $request)
    {
        $fileUrl = $request->fileUrl;
        if (empty($fileUrl)) {
            return errBack('缺少参数');
        }
        $aliyunUpload = new AliyunUploadServices();
        $data = $aliyunUpload->getUploadInformation($fileUrl);
        if ($data !== 1) {
            return okBack('0', ['data' => $data]);
        } else {
            return errBack('获取失败！');
        }
    }

}
